<template>
  <div class="warning-rule-management">
    <!-- 查询筛选区域 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryParams" inline>
     
         <el-form-item label="数据类型">
          <el-select
            v-model="queryParams.recordType"
            placeholder="请输入或选择类型"
            clearable
            filterable
            allow-create
            style="width: 220px"
         >
            <el-option label="全部" value="" />
            <el-option label="血压" value="血压" />
            <el-option label="心率" value="心率" />
            <el-option label="血糖" value="血糖" />
            <el-option label="血脂" value="血脂" />
            <!-- 其他类型 -->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="action-card" shadow="never">
      <el-button type="success" icon="Plus" @click="openAddDialog">新增规则</el-button>
      <el-button type="danger" icon="Delete" @click="batchDeleteRules">批量删除</el-button>
      <span style="margin-left: 20px;">共 <b>{{ total }}</b> 条规则</span>
    </el-card>

    <!-- 规则表格 -->
    <el-card class="content-card" shadow="never">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="recordType" label="数据类型" align="center" />
        <el-table-column label="测量值范围" align="center">
          <template #default="{ row }">
            <span v-if="row.recordType === '血压'">
              {{ row.minValue1 || '不限' }}~{{ row.maxValue1 || '不限' }} / {{ row.minValue2 || '不限' }}~{{ row.maxValue2 || '不限' }}
            </span>
            <span v-else>
              {{ row.minValue1 || '不限' }}~{{ row.maxValue1 || '不限' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column prop="updateTime" label="更新时间" align="center" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="{ row }">
            <el-button text type="primary" size="small" @click="editRule(row)">编辑</el-button>
            <el-button text type="danger" size="small" @click="deleteRule(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


       <el-pagination
        v-model:current-page="queryParams.current"
        :page-size="queryParams.size"
        :page-sizes="[5, 7, 9, 10]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="fetchData"
        style="margin-top: 16px; text-align: right;"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="addDialogVisible" :title="formData.id ? '编辑预警规则' : '新增预警规则'" width="600px">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <!-- <el-form-item label="数据类型" prop="recordType">
          <el-select v-model="formData.recordType" placeholder="请选择数据类型" @change="handleRecordTypeChange" style="width: 100%">
            <el-option label="血压" value="血压" />
            <el-option label="心率" value="心率" />
            <el-option label="血糖" value="血糖" />
            <el-option label="血脂" value="血脂" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="数据类型" prop="recordType">
  <el-select
    v-model="formData.recordType"
    placeholder="请选择或输入类型"
    filterable
    allow-create
    @change="handleRecordTypeChange"
    style="width: 100%"
    :disabled="formData.id !== null"
  >
    <el-option label="血压" value="血压" />
    <el-option label="心率" value="心率" />
    <el-option label="血糖" value="血糖" />
    <el-option label="血脂" value="血脂" />
  </el-select>
</el-form-item>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="测量值1最小值" prop="minValue1">
              <el-input v-model="formData.minValue1" placeholder="可为空" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="测量值1最大值" prop="maxValue1">
              <el-input v-model="formData.maxValue1" placeholder="可为空" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row  :gutter="10">
          <el-col :span="12">
            <el-form-item label="测量值2最小值" prop="minValue2">
              <el-input v-model="formData.minValue2" placeholder="可为空" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="测量值2最大值" prop="maxValue2">
              <el-input v-model="formData.maxValue2" placeholder="可为空" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入规则描述" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import warningRulesApi from '@/api/warningRules'

const existingTypes = ref([]) // 存储已有类型的列表
// 查询参数
const queryParams = reactive({
  recordType: '',
  current: 1,
  size: 5
})

// const isShowSecondValue = computed(() => formData.recordType === '血压')

// 表格数据相关
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 弹窗相关
const addDialogVisible = ref(false)
const formRef = ref(null)

// 表单数据
const defaultFormData = {
  id: null,
  recordType: '',
  minValue1: '',
  maxValue1: '',
  minValue2: '',
  maxValue2: '',
  description: '',
  status: 1
}

const formData = reactive({ ...defaultFormData })

// 表单规则
const formRules = {
  recordType: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ]
}

// 多选引用
const multipleTableRef = ref(null)
const multipleSelection = ref([])

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    console.log('查询参数:', queryParams)
    const response = await warningRulesApi.page( queryParams.current, queryParams.size,queryParams.recordType)
    tableData.value = response.records
    total.value = response.total
  } catch (e) {
    ElMessage.error('获取规则失败'+e)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {

  fetchData()
}

// 重置
const resetQuery = () => {
  queryParams.recordType = ''

  fetchData()
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    if (!formData.id && existingTypes.value.includes(formData.recordType)) {
      ElMessage.error('该数据类型已存在，请选择其他类型或编辑已有类型')
      return
    }


    try {
      if (formData.id) {
        await warningRulesApi.update(formData)
        ElMessage.success('更新成功')
      } else {
       
        await warningRulesApi.add(formData)
        ElMessage.success('新增成功')
      }

      addDialogVisible.value = false
      Object.assign(formData, defaultFormData)
      fetchData()
    } catch (e) {
      ElMessage.error(formData.id ? '更新失败' : '新增失败')
    }
  })
}

// 打开新增弹窗
const openAddDialog = () => {
  Object.assign(formData, defaultFormData)
  addDialogVisible.value = true
}

// 编辑
const editRule = (row) => {
  Object.assign(formData, row)
  addDialogVisible.value = true
}

// 删除
const deleteRule = (id) => {
  ElMessageBox.confirm('确定要删除该规则吗？', '提示', { type: 'warning' }).then(async () => {
    await warningRulesApi.deleteById(id)
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {})
}

// 批量删除
const batchDeleteRules = () => {
  const selectedIds = multipleSelection.value.map(item => item.id)
  if (selectedIds.length === 0) {
    ElMessage.warning('请至少选择一条规则')
    return
  }

  ElMessageBox.confirm('确定要删除选中的规则吗？', '提示', { type: 'warning' }).then(async () => {
    await warningRulesApi.batchDelete(selectedIds)
    ElMessage.success('批量删除成功')
    fetchData()
  }).catch(() => {ElMessage.error(e.message || '删除失败')})
}

// 处理多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 切换每页条数
const handleSizeChange = (newSize) => {
  queryParams.size = newSize
  fetchData()
}

// 数据类型切换时清空第二组输入
const handleRecordTypeChange = () => {
  if (formData.recordType !== '血压') {
    formData.minValue2 = ''
    formData.maxValue2 = ''
  }
}

const fetchExistingTypes = async () => {
  try {
    const response = await warningRulesApi.getExistingTypes() // 假设有一个获取已有类型的接口
    existingTypes.value = response
  } catch (e) {
    ElMessage.error('获取已有类型失败')
  }
}

onMounted(() => {
  fetchData()
  fetchExistingTypes() // 在页面加载时获取已有类型
})
</script>

<style scoped>
.warning-rule-management {
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;
}
.query-card, .action-card, .content-card {
  margin-bottom: 16px;
}
</style>